<% layout('/layouts/default.html', {title: '轮播图详情管理', libs: ['validate','fileupload']}){ %>
<div class="main-content">
    <div class="box box-main">
        <div class="box-header with-border">
            <div class="box-title">
                <i class="fa icon-note"></i> 编辑轮播图
            </div>
        </div>
        <#form:form id="inputForm" model="${carousel}" action="${ctx}/carousel/carousel/saveCarousel" method="post" class="form-horizontal">
            <div class="box-body">
                <div class="form-unit">${text('信息')}</div>
                <#form:hidden path="carouselId"/>
                <div class="row">
                    <div class="col-xs-4">
                        <div class="form-group">
                            <label class="control-label col-sm-2">
                                <span class="required">*</span> ${text('图片')}：</label>
                            <div class="col-sm-10">
                                <div class="custom-box">
                                    <div class="custom-center-title">
                                        <ul class="custom-ul" id="image"></ul>
                                        <div id="showBtn" class="custom-center">
                                            <i class="fa fa-image custom-icon"></i>
                                            <div class="custom-file">
                                                <span>点击选择图片</span>
                                                <input type="file" accept="image/*" class="cover-file" id="carousel">
                                            </div>
                                            <span class="custom-tips">最多可选择 1 张图片呦~</span>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="col-xs-4">
                        <div class="form-group">
                            <label class="control-label col-sm-4" title="">
                                <span class="required ">*</span> ${text('排序')}：<i class="fa icon-question hide"></i></label>
                            <div class="col-sm-8">
                                <#form:input path="sort" maxlength="10" class="form-control required digits"/>
                            </div>
                        </div>
                    </div>
                    <div class="col-xs-4">
                        <div class="form-group">
                            <label class="control-label col-sm-4" title="">
                                <span class="required ">*</span> ${text('状态')}：<i class="fa icon-question hide"></i></label>
                            <div class="col-sm-8">
                                <#form:radio path="carouselStatus" dictType="carousel_status" class="form-control required" />
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </#form:form>
        <div class="box-footer">
            <div class="row">
                <div class="col-sm-offset-2 col-sm-10">
                    <% if (hasPermi('carousel:carousel:edit')){ %>
                    <button type="submit" class="btn btn-sm btn-primary" id="btnSubmit"><i class="fa fa-check"></i> ${text('保 存')}</button>&nbsp;
                    <% } %>
                    <button type="button" class="btn btn-sm btn-default" id="btnCancel" onclick="js.closeCurrentTabPage()"><i class="fa fa-reply-all"></i> ${text('关 闭')}</button>
                </div>
            </div>
        </div>
    </div>
</div>
<% } %>
<script>
    let imgList = [],deleteInfo={carousel:[]};
    //图片初始显示
    const carousel = JSON.parse('${toJson(carousel)}'),baseUrl='${baseUrl}';
    if (carousel.carouselUrl !== undefined && carousel.carouselUrl !== ''){
        imgList = [{imageUrl:carousel.carouselUrl}];
        imgShow(0,imgList);
    }
    // 上传图片
    $('#carousel').on('change',function (e) {
        let img = e.target.files;
        const fix = (new Date()).getTime();
        for(let i=0;i<img.length;i++) {
            const name = (img[i].name).split('.');
            const file = new File([img[i]], 'carousel_' + (fix+i) + '.' + name[1]);
            file.imgType='new';
            imgList=imgList.concat(file);
        }
        imgShow(0,imgList);
    });
    // 显示图片列表
    function imgShow(index,attr){
        let html = '';
        let windowURL = window.URL || window.webkitURL;
        for(let i =0;i<attr.length;i++) {
            console.log("attr[i].imgType",attr[i].imgType)
            if(attr[i].imgType){
                let dataURL = windowURL.createObjectURL(attr[i]);
                html +='<li class="custom-li">' +
                    '<div class="custom-trash" onclick="removeImg('+ index +','+i+')"><i class="fa fa-trash custom-del"></i></div>' +
                    '<div><img class="custom-img" src="'+dataURL+'"></div>' +
                    '<div class="custom-load">等待上传</div>' +
                    '</li>';
                windowURL.revokeObjectURL(attr[i]);
            }else {
                let dataURL = baseUrl+attr[i].imageUrl;
                html +='<li class="custom-li">' +
                    '<div class="custom-trash" onclick="removeImg('+ index +','+i+')"><i class="fa fa-trash custom-del"></i></div>' +
                    '<div><img class="custom-img" src="'+dataURL+'"></div>' +
                    '<div class="custom-success">已上传</div>' +
                    '</li>';
            }
        }
        if(index==0){
            if(attr.length>0){
                $('#showBtn').hide();
            }else{
                $('#showBtn').show();
            }
            $('#image').html(html);
        }
    }
    // 移除图片
    function removeImg(index,obj){
        js.confirm('确认删除该图片吗？', function(){
            if(index==0){
                $.each(imgList,(index)=>{
                    if(index==obj){
                        if(!imgList[obj].imgType){
                            const img = imgList[obj].imageUrl.split("/");
                            deleteInfo.carousel.push(img[img.length-1])
                        }
                        imgList.splice(index,1);
                    }
                });
                imgShow(0,imgList);
            }
        });
    }

    // 保存
    $("#inputForm").validate({
        submitHandler: function(form){
            saveFileData();
        }
    });

    // 绑定提交按钮点击事件
    $("#btnSubmit").click(function(){
        // 先进行表单验证，如果验证通过会自动调用submitHandler
        if($("#inputForm").valid()){
            $("#inputForm").submit();
        }
    });

    // 保存
    function saveFileData(formData) {
        if(imgList.length==0){
            js.showMessage('轮播图片未上传！！');
            return;
        }

        if(imgList.length > 1){
            js.showMessage('最多只能上传1张图片！');
            return;
        }
        let paramsImg = new FormData();
        paramsImg.append("carouselId", $('#carouselId').val()); // 从表单获取
        paramsImg.append("sort", $('#sort').val()); // 从表单获取
        paramsImg.append("carouselStatus", $('input[name="carouselStatus"]:checked').val()); // 从表单获取
        paramsImg.append("delCarousel", deleteInfo.carousel.join(","));

        for(let i=0;i<imgList.length;i++){
            if(imgList[i].imgType){
                paramsImg.append('files',imgList[i]);
            }
        }
        js.confirm('确认提交吗？', function(){
            $.ajax({
                url : '${ctx}/carousel/carousel/saveCarousel',
                type : 'POST',
                data : paramsImg,
                dataType : 'JSON',
                contentType:false,
                processData:false,
                mimeType:"multipart/form-data",
                success : function(data) {
                    js.showMessage(data.message);
                    if(data.result == 'true'){
                        js.closeCurrentTabPage(function(contentWindow){
                            contentWindow.page();
                        });
                    }
                },error: function(xhr, status, error) {
                    js.showMessage('保存失败：' + error);
                }
            });
        });
    }

</script>